package QuestaoView;

import DisciplinaTopico.QuestaoDAOException;
import DisciplinaTopico.Topico;
import DisciplinaTopico.TopicoDAOException;
import DisciplinaTopicoView.TopicoDAO;
import Media.MediaController;
import Questao.Questao;
import java.awt.TrayIcon.MessageType;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;

public class QuestaoView extends javax.swing.JFrame
{
    private List<Topico> listaTopicos;
    private Questao questaoCorrente;
    private TopicoDAO topicoDAO;

    public QuestaoView(TopicoDAO topicoDAO)
    {
        initComponents();

        this.topicoDAO = topicoDAO;
        
        populaComboTopicos();
        
        ArrayList<Questao> questoes = new ArrayList<Questao>();
        for(Topico topico : listaTopicos)
            questoes.addAll(topico.getQuestoes());
        
        lbxQuestoes.setListData(questoes.toArray());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnExcluir = new javax.swing.JButton();
        btnAdicionar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        lbxQuestoes = new javax.swing.JList();
        jLabel7 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        cmbTopicos = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        btnFiltrar = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        cmbTopicos1 = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Módulo Questões");
        setMaximumSize(new java.awt.Dimension(400, 450));
        setName("frQuestao"); // NOI18N
        setResizable(false);

        btnExcluir.setText("Excluir");
        btnExcluir.setEnabled(false);
        btnExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExcluirActionPerformed(evt);
            }
        });

        btnAdicionar.setText("Adicionar");
        btnAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdicionarActionPerformed(evt);
            }
        });

        btnEditar.setText("Editar");
        btnEditar.setEnabled(false);
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        lbxQuestoes.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        lbxQuestoes.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        lbxQuestoes.setToolTipText("Lista de Questões");
        lbxQuestoes.setFixedCellHeight(15);
        lbxQuestoes.setFixedCellWidth(200);
        lbxQuestoes.setMaximumSize(new java.awt.Dimension(40, 40));
        lbxQuestoes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lbxQuestoesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(lbxQuestoes);

        jLabel7.setText("Lista de questões");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Filtros", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, new java.awt.Color(0, 0, 0)));

        cmbTopicos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbTopicosActionPerformed(evt);
            }
        });

        jLabel4.setText("Tópico:");

        btnFiltrar.setText("Filtrar");
        btnFiltrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFiltrarActionPerformed(evt);
            }
        });

        jLabel6.setText("Outro filtro:");

        cmbTopicos1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbTopicos1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnFiltrar))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(18, 21, Short.MAX_VALUE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jLabel4)
                                .addGap(40, 40, 40)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(cmbTopicos, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGap(1, 1, 1))
                            .addComponent(cmbTopicos1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(14, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbTopicos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbTopicos1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addGap(18, 18, 18)
                .addComponent(btnFiltrar)
                .addGap(32, 32, 32))
        );

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Módulo Questões");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jScrollPane1)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnAdicionar, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jLabel7))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addComponent(btnAdicionar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEditar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnExcluir))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
        if(JOptionPane.showConfirmDialog(null, "Deseja realmente excluir a questao selecionada?", "Confirmação de Exclusão", MessageType.INFO.ordinal()) == 0)
        {
            try
            {
                if(questaoCorrente != null)
                {
                    topicoDAO.excluirQuestao(topicoDAO.obterTopicoQuestao(questaoCorrente), questaoCorrente);
                    
                    defineEstadoInicial(false);

                    JOptionPane.showMessageDialog(null, "A exclusão da questão foi realizada com sucesso.", "Exclusão concluída", MessageType.INFO.ordinal(),MediaController.createImageIcon("Imagens/Success.png"));
                }
            }
            catch(QuestaoDAOException questaoEx)
            {
                MediaController.showErrorMessage("Não foi possível excluir a questao. Exception: " + questaoEx.getMessage(), "Erro na Exclusão");
            }
            catch(TopicoDAOException topicoEx)
            {
                MediaController.showErrorMessage("Não foi possível excluir a questao. Exception: " + topicoEx.getMessage(), "Erro na Exclusão");
            }
        }
  
}//GEN-LAST:event_btnExcluirActionPerformed

    private void btnAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarActionPerformed
        showPropertiesView(true);
}//GEN-LAST:event_btnAdicionarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        showPropertiesView(false);
}//GEN-LAST:event_btnEditarActionPerformed

    private void lbxQuestoesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbxQuestoesMouseClicked
        boolean temQuestaoSelecionada = !this.lbxQuestoes.isSelectionEmpty();

        if(temQuestaoSelecionada)
        {
            questaoCorrente = (Questao)this.lbxQuestoes.getSelectedValue();
            trocaStatusBotoes(true);
        }
}//GEN-LAST:event_lbxQuestoesMouseClicked

    private void cmbTopicosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTopicosActionPerformed
       
    }//GEN-LAST:event_cmbTopicosActionPerformed

    private void btnFiltrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFiltrarActionPerformed
        Topico topicoSelecionado = (Topico)this.cmbTopicos.getSelectedItem();

        if(topicoSelecionado != null)
        {
            List<Questao> questoes = topicoSelecionado.getQuestoes();

            if(questoes == null) //Se o Tópico não possui nenhuma questão associada
            {
                questoes = new ArrayList<Questao>();
            }
            
            this.lbxQuestoes.setListData(questoes.toArray());
            this.btnAdicionar.setEnabled(true);
        }
    }//GEN-LAST:event_btnFiltrarActionPerformed

    private void cmbTopicos1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTopicos1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbTopicos1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdicionar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnFiltrar;
    private javax.swing.JComboBox cmbTopicos;
    private javax.swing.JComboBox cmbTopicos1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList lbxQuestoes;
    // End of variables declaration//GEN-END:variables
    
    private void populaComboTopicos()
    {
        try
        {
            listaTopicos = topicoDAO.getTopicos();

            for (Topico topico : listaTopicos)
            {
                this.cmbTopicos.addItem(topico);
            }

            this.cmbTopicos.setSelectedIndex(0);
        }
        catch(TopicoDAOException topicoEx)
        {
            MediaController.showErrorMessage("Não foi possível preencher a caixa de seleção de Tópicos. Exception: " + topicoEx.getMessage(), "Erro nos topicos");
        }
    }
    
    private void defineEstadoInicial(boolean statusBotoes)
    {
         trocaStatusBotoes(statusBotoes);
    }
    
    private void trocaStatusBotoes(boolean habilita)
    {
        this.btnEditar.setEnabled(habilita);
        this.btnExcluir.setEnabled(habilita);
    }
    
    private void showPropertiesView(boolean isAddition)
    {
        try
        {
            PropriedadesQuestaoView telaPropriedadesQuestao = new PropriedadesQuestaoView(questaoCorrente, topicoDAO, isAddition);
            telaPropriedadesQuestao.setVisible(true);
        }
        catch (Exception ex)
        {
            MediaController.showErrorMessage("ERRO: Não foi possivel abrir o modulo de disciplina. \nDetalhes:" + ex.getMessage(),"Erro ao abrir modulo");
        }
    }
}